package com.zjj.filmcommentapi.interceptor;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.zjj.filmcommentapi.dao.UserMapper;
import com.zjj.filmcommentapi.model.User;
import com.zjj.filmcommentapi.utils.RedisUtil;
import com.zjj.filmcommentapi.utils.annotation.PassToken;
import com.zjj.filmcommentapi.utils.annotation.UserToken;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.List;

/**
 * 验证token的拦截器
 */
public class AuthenticationInterceptor implements HandlerInterceptor {
    @Autowired
    UserMapper userMapper;
    @Resource
    RedisUtil redisUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String cookie = request.getHeader("Cookie");
        String token = cookie.substring(cookie.indexOf("sessionId=")+10);// 从http请求头中取出token
        // 如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        // 检查是否有passtoken注解，有则跳过认证
        if (method.isAnnotationPresent(PassToken.class)) {
            PassToken passToken = method.getAnnotation(PassToken.class);
            if (passToken.required()) {
                return true;
            }
        }
        // 检查是否有usertoken的注解
        if (method.isAnnotationPresent(UserToken.class)) {
            UserToken userToken = method.getAnnotation(UserToken.class);
            if (userToken.required()) {
                // 执行认证
                if (StringUtils.isBlank(token)) {
                    throw new RuntimeException("无token，请重新登录");
                }
                // 获取token中的account
                String account;
                try {
                    account = JWT.decode(token).getAudience().get(0);
                } catch (JWTDecodeException j) {
                    throw new RuntimeException("401");
                }catch (Exception e){
                    throw new RuntimeException("401");
                }
                List tokenList = redisUtil.getList(account,0,-1);
               if (!tokenList.contains(token)){
                   throw  new RuntimeException("token无效，请重新登录");
               }
                // 验证token
                Boolean hasToken = redisUtil.hasKey(token);
                if (!hasToken){
                    throw new RuntimeException("token无效，请重新登录");
                }
                Long expired = redisUtil.getTokenExpire(token);
                if (expired <= 0L) {
                    throw new RuntimeException("token过期，请重新登录");
                }
                User user = (User) redisUtil.sentinelGet(token);
                if (user == null) {
                    throw new RuntimeException("用户不存在");
                }
                // jwt验证 解密验证token
                try {
                    JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
                    jwtVerifier.verify(token); // jwt= jwtVerifier.verify(token); jwt.getClaim("key").asString() 可以解析出数
                    redisUtil.renewToken(token, user);
                } catch (JWTVerificationException E) {
                    throw new RuntimeException("401");
                }
                return true;
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
